/**
 * 防抖按钮
 * @author lawrence
 * @date 2019-03-14
 */
import React, {PureComponent} from "react";
import {TouchableOpacity, ViewPropTypes} from "react-native";

type Props = {
    effectTime: number,                     // 防抖时间
    disabledStyle: ViewPropTypes.style      // 按钮未激活样式
}

type State = {}

const DEBOUNCE_MILLISECOND = 300;   // 多次点击，响应间隔时间

export default class TouchableRabbit extends PureComponent<Props, State> {

    static defaultProps = {
        effectTime: DEBOUNCE_MILLISECOND,
        disableStyle: null,
    };

    _lastClickTime = 0;    // 最后一次点击按钮时间

    render() {
        const {disabled, disabledStyle, onPress, style, activeOpacity} = this.props;
        return (
            <TouchableOpacity
                {...this.props}
                style={disabled ? disabledStyle : style}
                activeOpacity={activeOpacity ? activeOpacity : 0.8}
                onPress={() => !disabled && this._debouncePress(onPress)}
            >
                {this.props.children}
            </TouchableOpacity>
        )
    }

    _enable = () => {
        const {props: {effectTime}, _lastClickTime} = this;
        const time = Date.now();
        const enable = !_lastClickTime || Math.abs(_lastClickTime - time) > effectTime;
        enable && (this._lastClickTime = time);
        return enable;
    };

    _debouncePress = onPress => {
        this._enable() && !!onPress && onPress();
    }

}
